package org.xue.snowmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import entity.GoodsEntity;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xue.snowmall.common.utils.R;

import java.io.IOException;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.xue.snowmall.common.utils.PageUtils;
import org.xue.snowmall.common.utils.Query;

import org.xue.snowmall.product.dao.GoodsDao;
import org.xue.snowmall.product.service.GoodsService;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<GoodsEntity> wrapper = new QueryWrapper<>();
        //条件查询
        IPage<GoodsEntity> page = this.page(
                new Query<GoodsEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public R up(Long psmId) throws IOException {

        //上架操作
        GoodsEntity goodsEntity = baseMapper.selectById(psmId);
        IndexRequest indexRequest = new IndexRequest("snow-goods");
        indexRequest.id(psmId + "").source(JSON.toJSONString(goodsEntity), XContentType.JSON);
        client.index(indexRequest, RequestOptions.DEFAULT);

        goodsEntity.setPsmStatus("0");
        baseMapper.updateById(goodsEntity);
        return R.ok();
    }

    @Override
    public R down(Long psmId) throws IOException {

        DeleteRequest deleteRequest = new DeleteRequest("snow-goods");

        client.delete(deleteRequest.id(psmId + ""), RequestOptions.DEFAULT);

        return R.ok();
    }

}